package com.thoughtworks.android.androsphere.service;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.util.Log;
import com.thoughtworks.android.androsphere.framework.UserEmailFetcher;

public class RegistrationServiceClient implements ServiceClient {
    private static final String TAG = RegistrationServiceClient.class.getName();

    Context context;
    String registrationId;

    public RegistrationServiceClient(Context context, String registrationId) {
        this.context = context;
        this.registrationId = registrationId;
    }

    public void execute() {
        Log.d(TAG, "Inside RegistrationServiceClient execute method");
        final String userEmail = UserEmailFetcher.getEmail(context);
        final String requestString = "device:" + userEmail + ";registration:" + registrationId + ";";

        final String registrationServiceUrl = context.getResources().getString(com.thoughtworks.android.androsphere.R.string.app_server_base_url) + "register";

        putData(registrationServiceUrl, requestString);
    }

    private void putData(final String url, final String requestString) {
        Log.d(TAG, "Invoking PUT request with URL : " +  url + ", request : " + requestString);

        HttpClient httpclient = new DefaultHttpClient();
        HttpPut httpPut = new HttpPut(url);
        try {
            httpPut.setEntity(new ByteArrayEntity(requestString.getBytes()));
            httpPut.setHeader("Content-Type", "text/plain");

            HttpResponse response = httpclient.execute(httpPut);
            Log.d(TAG, "Successful RegistrationService Call");            
        } catch (IOException e) {
            Log.e(TAG, "Failed to send registration ID to app server : " + e.getMessage());
        }
        finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
}
